package com.atguigu.srb.core.controller.api;


import com.alibaba.fastjson.JSON;
import com.atguigu.common.result.R;
import com.atguigu.srb.base.utils.JwtUtils;
import com.atguigu.srb.core.hfb.RequestHelper;
import com.atguigu.srb.core.pojo.entity.LendItem;
import com.atguigu.srb.core.pojo.vo.InvestVO;
import com.atguigu.srb.core.service.LendItemService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 标的出借记录表 前端控制器
 * </p>
 *
 * @author tjf
 * @since 2022-01-03
 */
@RestController
@Slf4j
@Api(tags = "标的的投资")
@RequestMapping("/api/core/lendItem")
public class LendItemController {
    LendItemService lendItemService;

    public LendItemController(LendItemService lendItemService) {
        this.lendItemService = lendItemService;
    }

    @ApiOperation("会员投资提交数据")
    @PostMapping("/auth/commitInvest")
    public R commitInvest(@RequestBody InvestVO investVO, @RequestHeader String token) {
        Long userId = JwtUtils.getUserId(token);
        String userName = JwtUtils.getUserName(token);
        investVO.setInvestUserId(userId);
        investVO.setInvestName(userName);

        String formStr = lendItemService.commitInvest(investVO);
        return R.ok().data("formStr", formStr);
    }

    @ApiOperation("会员投资异步回调接口")
    @PostMapping("/notify")
    public String notify(HttpServletRequest httpServletRequest) {
        // 获取汇付宝回调时携带的参数
        Map<String, Object> map = RequestHelper.switchMap(httpServletRequest.getParameterMap());
        log.info("会员投资异步回调接收参数如下：" + JSON.toJSONString(map));

        // 校验签名
        if (!RequestHelper.isSignEquals(map)) {
            log.error("会员投资绑定异步回调签名验证错误：" + JSON.toJSONString(map));
            return "fail";
        }

        if ("0001".equals(map.get("resultCode"))) {
            log.info("验证签名成功，开始充值账户");

            return lendItemService.notify(map);

        }
        return "success";
    }

    @ApiOperation("获取列表")
    @GetMapping("/list/{lendId}")
    public R list(@ApiParam("标的id") @PathVariable Long lendId) {
        List<LendItem> list = lendItemService.selectByLendId(lendId);
        return R.ok().data("list", list);
    }
}

